package com.crazymaker.springcloud.demo.security;

import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.standard.context.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Service
public class DemoAuthUserService implements UserDetailsService {

    private Map<String, String> map = new LinkedHashMap<>();

    {
        map.put("zhangsan", "123456");
        map.put("lisi", "111111");
    }

    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String password = map.get(s);
        if (StringUtils.isEmpty(password)){
            log.error("用户：{}不存在", s);
            return null;
        }

        if (passwordEncoder == null) {
            passwordEncoder = SpringContextUtil.getBean(PasswordEncoder.class);
        }


        return User.builder().username(s)
                // 数据库密码
                .password(passwordEncoder.encode(password))
                .authorities(SessionConstants.USER_INFO)
                .roles("USER")
                .build();
    }
}
